const express = require('express')
const { readJsonAsObject, writeObjectAsJson } = require('./utils')


const app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: false }))


const DATA_FILE = 'data.json'


try {
    var obj = readJsonAsObject(DATA_FILE)
}
catch (e) {
    var obj = {
        "id_next": 1,
        "list": [
        ]
    }
    writeObjectAsJson(DATA_FILE, obj)
}


app.post('/add', function(req, res) {
    var new_task = {
        "id": obj.id_next,
        "title": "作业",
        "add_time": Date.now(),
        "stop_time": req.body.stop_time,
        "is_finish": false
    }
    obj.list.push(new_task)
    obj.id_next += 1
    writeObjectAsJson(DATA_FILE, obj)
    res.send(new_task)
})


app.post('/all', function(req, res) {
    res.send({
        "list": obj.list
    })
})


app.listen(3000, '0.0.0.0', function() {
    console.log('Server start at http://127.0.0.1:3000')
})
